package com.py.custom.tms.application.jvm.classload;

import java.sql.Driver;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 线程上下文类加载器 的使用模式：获取、使用、还原
 *
 * ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 * try{
 *      Thread.currentThread().setContextClassLoader(targetTccl);
 *      myMethod();
 * } finally {
 *     Thread.currentThread().setContextClassLoader(classLoader);
 * }
 */
public class MyTest26 {

    public static void main(String[] args) {
        ServiceLoader<Driver> serviceLoader = ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = serviceLoader.iterator();

        while (iterator.hasNext()) {
            // 引入Mysql的驱动就会被加载；jar包中存在：META/INF/java.sql.Driver 文件
            Driver driver = iterator.next();
            System.out.println(driver);
        }

        System.out.println("当前线程上下文类加载器: " + Thread.currentThread().getContextClassLoader());
        System.out.println("ServiceLoader的类加载：" + ServiceLoader.class.getClassLoader());
    }
}
